package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import net.bytebuddy.implementation.auxiliary.AuxiliaryType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.IIOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    ReportMapper reportMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> localDates = new ArrayList<>(); // 查询date
        ArrayList<Double> statistics = new ArrayList<>(); // 查询date对应的营业额

        do {
            localDates.add(begin);

            // 获取当前要查时间范围
            LocalDateTime currentStart = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime currentEnd = LocalDateTime.of(begin, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("begin", currentStart);
            map.put("end", currentEnd);
            map.put("status", Orders.COMPLETED);

            // 查询
            Double total = reportMapper.getStatistics(map);
            statistics.add(total != null ? total : 0.0);
            begin = begin.plusDays(1);
        } while (!begin.isAfter(end));

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(localDates, ','))
                .turnoverList(StringUtils.join(statistics, ','))
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 日期列表、当日新增用户、累加用户数量
        ArrayList<LocalDate> localDates = new ArrayList<>();
        ArrayList<Integer> userAdd = new ArrayList<>();
        ArrayList<Integer> userTotal = new ArrayList<>();

        // 先获取累加基数
        HashMap<String, Object> map = new HashMap<>();
        map.put("end", LocalDateTime.of(begin.plusDays(-1), LocalTime.MAX));
        Integer total = userMapper.getTotal(map);

        do {
            localDates.add(begin);

            map = new HashMap<>();
            map.put("begin", LocalDateTime.of(begin, LocalTime.MIN));
            map.put("end", LocalDateTime.of(begin, LocalTime.MAX));
            Integer current = userMapper.getTotal(map);

            userAdd.add(current);
            total += current;
            userTotal.add(total);

            begin = begin.plusDays(1);
        } while (!begin.isAfter(end));

        return UserReportVO.builder()
                .dateList(StringUtils.join(localDates, ','))
                .newUserList(StringUtils.join(userAdd, ','))
                .totalUserList(StringUtils.join(userTotal, ','))
                .build();
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {

        // 初始化数据列表
        ArrayList<LocalDate> localDates = new ArrayList<>();
        ArrayList<Integer> ordersTotal = new ArrayList<>();
        ArrayList<Integer> completeTotal = new ArrayList<>();

        do {
            localDates.add(begin);
            HashMap<String, Object> map = new HashMap<>();

            // 单日点单数
            map.put("begin", LocalDateTime.of(begin, LocalTime.MIN));
            map.put("end", LocalDateTime.of(begin, LocalTime.MAX));
            Integer total = orderMapper.getOrdersCount(map);
            ordersTotal.add(total);

            // 单日有效单数
            map.put("status", Orders.COMPLETED);
            Integer validTotal = orderMapper.getOrdersCount(map);
            completeTotal.add(validTotal);

            begin = begin.plusDays(1);
        } while (!begin.isAfter(end));

        Integer allTotal = ordersTotal.stream().reduce(Integer::sum).get();
        Integer allCompleteTotal = completeTotal.stream().reduce(Integer::sum).get();

        return OrderReportVO.builder()
                .dateList(StringUtils.join(localDates, ','))
                .orderCountList(StringUtils.join(ordersTotal, ','))
                .validOrderCountList(StringUtils.join(completeTotal, ','))
                .totalOrderCount(allTotal)
                .validOrderCount(allCompleteTotal)
                .orderCompletionRate((double) allCompleteTotal / allTotal)
                .build();
    }

    @Override
    public SalesTop10ReportVO getTopDish(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);


        List<GoodsSalesDTO> result = reportMapper.getTop10(beginTime, endTime);
        List<String> nameList = result.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = result.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ','))
                .numberList(StringUtils.join(numberList, ','))
                .build();
    }

    @Override
    public void export(HttpServletResponse response) {
        // 查询 30 天的营运数据
        LocalDate startDay = LocalDate.now().plusDays(-30);
        LocalDate yesterday = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(startDay, LocalTime.MIN), LocalDateTime.of(yesterday, LocalTime.MAX));
        System.out.println(businessData);

        // 通过 POI 向 Excel 写入数据
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            assert in != null;
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet1 = excel.getSheet("Sheet1");

            // 1.填充报表时间数据
            sheet1.getRow(1).getCell(1).setCellValue("时间：" + startDay + " 到 " + yesterday);

            // 2.填充业务总览
            XSSFRow row = sheet1.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            row = sheet1.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            // 填充明细
            LocalDate date;
            for (int i = 0; i < 30; i++) {
                // 查询数据
                date = startDay.plusDays(i);
                BusinessDataVO currentData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                row = sheet1.getRow(i + 7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(currentData.getTurnover());
                row.getCell(3).setCellValue(currentData.getValidOrderCount());
                row.getCell(4).setCellValue(currentData.getOrderCompletionRate());
                row.getCell(5).setCellValue(currentData.getUnitPrice());
                row.getCell(6).setCellValue(currentData.getNewUsers());
            }

            // 输出流将文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            out.close();
            excel.close();
            
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
